#pragma once
#include <iostream>
#include "Sock.hpp"
#include "Log.hpp"
#include <functional>
#include<signal.h>
#include<string>
#include <unistd.h>

class HttpServer
{
public:
    using func_t = std::function<void(int)>;
private:
    int listensock_;
    uint16_t port_;
    Sock sock_;
    func_t func_;
public:
    HttpServer(const uint16_t &port,func_t func):port_(port),func_(func)
    {
        listensock_ = sock_.Socket();
        sock_.Bind(listensock_,port_);
        sock_.Listen(listensock_);
    }
    void Start()
    {
        signal(SIGCHLD,SIG_IGN);
        while(true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = sock_.Accept(listensock_,&clientip,&clientport);
            if(sockfd<0)
                continue;
            if(fork()==0)
            {
                close(listensock_);
                func_(sockfd);
                close(sockfd);
                exit(0);
            }
            close(sockfd);
        }
    }
    ~HttpServer()
    {
        if(listensock_>=0)
        {
            close(listensock_);
        }
    }
};
